/*
 * =====================================================================================
 *
 *       Filename:  bin_search.c
 *
 *    Description:  search the last num in an array that less than the target number.
 *
 *        Created:  2020-07-31 14:50
 *
 *         Author:  limingle
 *          Email:  lml@xdja.com
 *   Organization:  XDJA Tech.CO.ltd.
 *
 * =====================================================================================
 */

#include <stdio.h>

int * bin_search(int a[], int n, int target)
{
    if (n <= 1)
    {
        return a[0] < target ? &a[0] : NULL;
    }
    else
    {
        int mid = (n-1)/2;
        return a[mid] < target? a[mid + 1] < target? bin_search(&a[mid+1], n - mid - 1, target) : &a[mid] : bin_search(a, mid, target);
    }
}

int bsearch(int a[], int n, int target)
{
    int *addr = bin_search(a, n, target);

    if (NULL == addr)
    {
        return -1;
    }
    else
    {
        printf("result %d\t%p\n", *addr, addr);
        return *addr;
    }
}

int main(int argc, const char *argv[])
{
    int a[] = {-4, 1, 2, 2, 5, 5, 5, 8, 10};
    int target = 6;

    int len = sizeof(a)/sizeof(a[0]);

    for (int i = 0; i < len; i++) {
        printf("a[%d]  %2d\t%p\n", i, a[i], &a[i]);
    }

    printf("%d\n", bsearch(a, sizeof(a)/sizeof(a[0]), target));

    return 0;
}
